﻿using System;
using System.Collections;
using System.Threading;
using S22.Imap;
using ConfigLibrary;
using MailClient.Data.IndexTables;
using System.Net.Mail;

namespace MailClient.Mail
{
	public class mail
	{
		private ImapClient client;
		//        private Mailbox mbx;
		private readonly ArrayList _tree = new ArrayList ();
		private Config config;
		private System.Timers.Timer tm;
		private Queue.IncomingRunner incoming;

		public mail ()
		{
			// Constructor connects and logs in
			client = Connections.connections.Client;
			GC.SuppressFinalize (client);
			MailClient.Queue.outgoingrunner.outgoing.SetImapClient (ref client);
			client.NewMessage += new EventHandler<IdleMessageEventArgs> (client_NewMessage);
			//            client.NewMessage += (sender, e) => {
			//                var msgs = client.SearchMessages(SearchCondition.Unseen());
//
			//                for (int i = 0; i < msgs.Length; i++)
			//                {
			//                    var msg = msgs[i].Value;
			//                    Console.WriteLine(msg.Subject);
			//                    try { ProcessEmail(msg); }
			//                    catch
			//                    {
			//                        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
			//                        mail.To.Add(new System.Net.Mail.MailAddress("bcrawford@rhaaia.com"));
			//                        mail.Subject = string.Format("Failed to process message subject:{0)", msg.Subject);
			//                        mail.Body = msg.Body;
			//                        MailClient.Queue.outgoingrunner.outgoing.sendmail(mail);
			//                    }
			//                }
			//            };
			// client.Namespace();
			//            Namespace PublicFolder = new Namespace("Public Folders", "/");
			//Mailbox[] mbxs=   client.ListMailboxes(PublicFolder.Prefix + PublicFolder.Delimiter, "*0002 Contacts*");
			//client.GetMessageCount(PublicFolder.Prefix + PublicFolder.Delimiter+"0002 Contacts");
			Console.ReadLine ();
			//client.MessageDeleted += new EventHandler<S22.Imap.Imap.MessageEventArgs>(client_MessageDeleted);
			//Start();
			
			
		}

		~mail ()
		{
			GC.ReRegisterForFinalize (client);
		}

		void client_MessageDeleted (object sender, IdleMessageEventArgs e)
		{
			//throw new NotImplementedException();
		}

		void client_NewMessage (object sender, IdleMessageEventArgs e)
		{
			//            client.SelectMailbox("INBOX");
			//            string[] msgstring = client.Search(SearchCondition.Unseen(), true);

			//            foreach (string s in msgstring)
			//            {
			//                Console.WriteLine(s);
			//                MailMessage msg = client.GetMessage(s, false);
			//                try { ProcessEmail(msg); }
			//                catch
			//                {
			//                    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
			//                    mail.To.Add(new System.Net.Mail.MailAddress("bcrawford@rhaaia.com"));
			//                    mail.Subject = string.Format("Failed to process message subject:{0)", msg.Subject);
			//                    mail.Body = msg.Body;
			//                    MailClient.Queue.outgoingrunner.outgoing.sendmail(mail);
			//                }

			Console.WriteLine ("New message arrived UID: {0}", e.MessageUID);
			MailMessage msg = e.Client.GetMessage (
				e.MessageUID,
				FetchOptions.NoAttachments
			);
			Console.WriteLine ("with subject {0}", msg.Subject);
			
			
			// if i do the next, it needs to be run on a thread pool
			//Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ProcessEmail));
			//t.Start(msg);
		}
	

		/// <summary>
		/// Starts a IMAP client to the RHA mail server.  Uses the logon info provided in the prefences
		/// </summary>
		public void Start ()
		{
//		client.SelectMailbox("INBOX");
			// Namespaces ImapNameSpaces = client.Namespace();

//		string[] msgstring = client.Search(SearchCondition.Unseen(), true);
//		foreach (string s in msgstring)
//		{
//			Console.WriteLine(s);
//			MailMessage msg = client.GetMessage(s, false);
//			ProcessEmail(msg);
//		}

			//    // if i do the next, it needs to be run on a thread pool
			//    //System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ProcessEmail));
			//    //t.Start(msg);
		
		}

		private void ProcessEmail (object mail)
		{
			MailMessage msg = (MailMessage)mail;
			incoming = new Queue.IncomingRunner (msg, ref client);
			incoming.CommandComplete += new Queue.IncomingRunner.CommandCompleteHandler (incoming_CommandComplete);

			incoming.Process ();

		}

		void incoming_CommandComplete (MailClient.Queue.MessageEventArgs e)
		{
			incoming.CommandComplete -= new Queue.IncomingRunner.CommandCompleteHandler (incoming_CommandComplete);
			lock (client) {
				client.SetFlags (Flags.Seen, e.Msg);
			}
			Thread.Sleep (300);
			NotSpamIndex.Index.Save ();
			SpamIndex.Index.Save ();
			MerchIndex.Index.Save ();
			BrandIndex.Index.Save ();
			CivilIndex.Index.Save ();
			CityIndex.Index.Save ();
			FuelIndex.Index.Save ();
			GeoIndex.Index.Save ();
			ShellIndex.Index.Save ();
			WaterIndex.Index.Save ();
			StoreIndex.Index.Save ();
			PersonIndex.Index.Save ();
		}


	}



}
